package org.example;

import lombok.extern.slf4j.Slf4j;
import org.example.config.RegistryConfig;
import org.example.config.RpcConfig;
import org.example.constant.RpcConstant;
import org.example.registry.Registry;
import org.example.registry.RegistryFactory;
import org.example.utils.ConfigUtils;

/**
 * Hello world!
 *
 */
@Slf4j
public class RpcApp
{
    private static volatile RpcConfig rpcConfig;

    public static void init(RpcConfig newRpcConfig){

        rpcConfig = newRpcConfig;
        log.info("rpc init, config = {}", newRpcConfig.toString());
        // 注册中心初始化
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);
        log.info("初始化注册中心成功, registry = {}", registryConfig.getRegistry());

        // 创建并注册ShutdownHook(当程序正常退出是会执行注册中心 的destory方法)
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }

    public static void init(){
        RpcConfig newRpcConfig;
        try {
            newRpcConfig = ConfigUtils.loadConfig(RpcConfig.class, RpcConstant.DEFAULT_PREFIX);
        } catch (Exception e){
            newRpcConfig = new RpcConfig();
        }
        init(newRpcConfig);
    }

    public static RpcConfig getRpcConfig(){
        if(rpcConfig == null){
            synchronized (RpcApp.class){
                if(rpcConfig == null){
                    init();
                }
            }
        }
        return rpcConfig;
    }

    public static void main( String[] args )
    {

        System.out.println( "Hello World!" );
    }
}
